home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / ohlutil.zip / LS.C < prev    next >
C/C++ Source or Header  |  1990-06-22  |  41KB  |  1,850 lines

  1. /* `dir', `vdir' and `ls' directory listing programs for GNU.
  2.    Copyright (C) 1985, 1988, 1989, 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* If the macro MULTI_COL is defined,
  19.    the multi-column format is the default regardless
  20.    of the type of output device.
  21.    This is for the `dir' program.
  22.  
  23.    If the macro LONG_FORMAT is defined,
  24.    the long format is the default regardless of the
  25.    type of output device.
  26.    This is for the `vdir' program.
  27.  
  28.    If neither is defined,
  29.    the output format depends on whether the output
  30.    device is a terminal.
  31.    This is for the `ls' program. */
  32.  
  33. /* Written by Richard Stallman and David MacKenzie. */
  34.  
  35. #include <sys/types.h>
  36. #ifdef _POSIX_SOURCE
  37. #define S_IEXEC S_IXUSR
  38. #else
  39. #include <sys/ioctl.h>
  40. #endif
  41. #include <stdio.h>
  42. #include <grp.h>
  43. #include <pwd.h>
  44. #include "getopt.h"
  45. #include "system.h"
  46.  
  47. /* Return an int indicating the result of comparing two longs. */
  48. #ifdef INT_16_BITS
  49. #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b) ? 1 : 0)
  50. #else
  51. #define longdiff(a, b) ((a) - (b))
  52. #endif
  53.  
  54. #ifdef STDC_HEADERS
  55. #include <errno.h>
  56. #include <stdlib.h>
  57. #include <time.h>
  58. #else
  59. char *ctime ();
  60. char *getenv ();
  61. char *malloc ();
  62. char *realloc ();
  63. long time ();
  64.  
  65. extern int errno;
  66. #endif
  67.  
  68. struct group *getgrgid ();
  69. struct passwd *getpwuid ();
  70. int glob_match ();
  71. void mode_string ();
  72.  
  73. char *copystring ();
  74. char *getgroup ();
  75. char *getuser ();
  76. char *make_link_path ();
  77. char *xmalloc ();
  78. char *xrealloc ();
  79. int compare_atime ();
  80. int rev_cmp_atime ();
  81. int compare_ctime ();
  82. int rev_cmp_ctime ();
  83. int compare_mtime ();
  84. int rev_cmp_mtime ();
  85. int compare_size ();
  86. int rev_cmp_size ();
  87. int compare_name ();
  88. int rev_cmp_name ();
  89. int decode_switches ();
  90. int file_interesting ();
  91. int gobble_file ();
  92. int is_not_dot_or_dotdot ();
  93. int length_of_file_name_and_frills ();
  94. void add_ignore_pattern ();
  95. void attach ();
  96. void clear_files ();
  97. void error ();
  98. void extract_dirs_from_files ();
  99. void get_link_name ();
  100. void indent ();
  101. void invalid_arg ();
  102. void print_current_files ();
  103. void print_dir ();
  104. void print_file_name_and_frills ();
  105. void print_horizontal ();
  106. void print_long_format ();
  107. void print_many_per_line ();
  108. void print_name_with_quoting ();
  109. void print_type_indicator ();
  110. void print_with_commas ();
  111. void queue_directory ();
  112. void sort_files ();
  113. void usage ();
  114.  
  115. enum filetype
  116. {
  117.   symbolic_link,
  118.   directory,
  119.   arg_directory,        /* Directory given as command line arg. */
  120.   normal            /* All others. */
  121. };
  122.  
  123. struct file
  124. {
  125.   /* The file name. */
  126.   char *name;
  127.  
  128.   struct stat stat;
  129.  
  130.   /* For symbolic link, name of the file linked to, otherwise zero. */
  131.   char *linkname;
  132.  
  133.   /* For symbolic link and long listing, st_mode of file linked to, otherwise
  134.      zero. */
  135.   unsigned int linkmode;
  136.  
  137.   enum filetype filetype;
  138. };
  139.  
  140. /* The table of files in the current directory:
  141.  
  142.    `files' points to a vector of `struct file', one per file.
  143.    `nfiles' is the number of elements space has been allocated for.
  144.    `files_index' is the number actually in use.  */
  145.  
  146. /* Address of block containing the files that are described.  */
  147.  
  148. struct file *files;
  149.  
  150. /* Length of block that `files' points to, measured in files.  */
  151.  
  152. int nfiles;
  153.  
  154. /* Index of first unused in `files'.  */
  155.  
  156. int files_index;
  157.  
  158. /* Record of one pending directory waiting to be listed.  */
  159.  
  160. struct pending
  161. {
  162.   char *name;
  163.   /* If the directory is actually the file pointed to by a symbolic link we
  164.      were told to list, `realname' will contain the name of the symbolic
  165.      link, otherwise zero. */
  166.   char *realname;
  167.   struct pending *next;
  168. };
  169.  
  170. struct pending *pending_dirs;
  171.  
  172. /* Current time (seconds since 1970).  When we are printing a file's time,
  173.    include the year if it is more than 6 months before this time.  */
  174.  
  175. long current_time;
  176.  
  177. /* The number of digits to use for block sizes.
  178.    4, or more if needed for bigger numbers.  */
  179.  
  180. int block_size_size;
  181.  
  182. /* The name the program was run with, stripped of any leading path. */
  183. char *program_name;
  184.  
  185. /* Option flags */
  186.  
  187. /* long_format for lots of info, one per line.
  188.    one_per_line for just names, one per line.
  189.    many_per_line for just names, many per line, sorted vertically.
  190.    horizontal for just names, many per line, sorted horizontally.
  191.    with_commas for just names, many per line, separated by commas.
  192.  
  193.    -l, -1, -C, -x and -m control this parameter.  */
  194.  
  195. enum format
  196. {
  197.   long_format,            /* -l */
  198.   one_per_line,            /* -1 */
  199.   many_per_line,        /* -C */
  200.   horizontal,            /* -x */
  201.   with_commas            /* -m */
  202. };
  203.  
  204. enum format format;
  205.  
  206. /* Type of time to print or sort by.  Controlled by -c and -u.  */
  207.  
  208. enum time_type
  209. {
  210.   time_mtime,            /* default */
  211.   time_ctime,            /* -c */
  212.   time_atime            /* -u */
  213. };
  214.  
  215. enum time_type time_type;
  216.  
  217. /* The file characteristic to sort by.  Controlled by -t, -S, and -U. */
  218.  
  219. enum sort_type
  220. {
  221.   sort_none,            /* -U */
  222.   sort_name,            /* default */
  223.   sort_time,            /* -t */
  224.   sort_size            /* -S */
  225. };
  226.  
  227. enum sort_type sort_type;
  228.  
  229. /* Direction of sort.
  230.    0 means highest first if numeric,
  231.    lowest first if alphabetic;
  232.    these are the defaults.
  233.    1 means the opposite order in each case.  -r  */
  234.  
  235. int sort_reverse;
  236.  
  237. /* Nonzero means print the user and group id's as numbers rather
  238.    than as names.  -n  */
  239.  
  240. int numeric_users;
  241.  
  242. /* Nonzero means mention the size in 512 byte blocks of each file.  -s  */
  243.  
  244. int print_block_size;
  245.  
  246. /* Nonzero means show file sizes in kilobytes instead of blocks
  247.    (the size of which is system-dependant).  -k */
  248.  
  249. int kilobyte_blocks;
  250.  
  251. /* none means don't mention the type of files.
  252.    all means mention the types of all files.
  253.    not_programs means do so except for executables.
  254.  
  255.    Controlled by -F and -p.  */
  256.  
  257. enum indicator_style
  258. {
  259.   none,                /* default */
  260.   all,                /* -F */
  261.   not_programs            /* -p */
  262. };
  263.  
  264. enum indicator_style indicator_style;
  265.  
  266. /* Nonzero means mention the inode number of each file.  -i  */
  267.  
  268. int print_inode;
  269.  
  270. /* Nonzero means when a symbolic link is found, display info on
  271.    the file linked to.  -L  */
  272.  
  273. int trace_links;
  274.  
  275. /* Nonzero means when a directory is found, display info on its
  276.    contents.  -R  */
  277.  
  278. int trace_dirs;
  279.  
  280. /* Nonzero means when an argument is a directory name, display info
  281.    on it itself.  -d  */
  282.  
  283. int immediate_dirs;
  284.  
  285. /* Nonzero means don't omit files whose names start with `.'.  -A */
  286.  
  287. int all_files;
  288.  
  289. /* Nonzero means don't omit files `.' and `..'
  290.    This flag implies `all_files'.  -a  */
  291.  
  292. int really_all_files;
  293.  
  294. /* A linked list of shell-style globbing patterns.  If a non-argument
  295.    file name matches any of these patterns, it is omitted.
  296.    Controlled by -I.  Multiple -I options accumulate.
  297.    The -B option adds `*~' and `.*~' to this list.  */
  298.  
  299. struct ignore_pattern
  300. {
  301.   char *pattern;
  302.   struct ignore_pattern *next;
  303. };
  304.  
  305. struct ignore_pattern *ignore_patterns;
  306.  
  307. /* Nonzero means quote nongraphic chars in file names.  -b  */
  308.  
  309. int quote_funny_chars;
  310.  
  311. /* Nonzero means output nongraphic chars in file names as `?'.  -q  */
  312.  
  313. int qmark_funny_chars;
  314.  
  315. /* Nonzero means output each file name using C syntax for a string.
  316.    Always accompanied by `quote_funny_chars'.
  317.    This mode, together with -x or -C or -m,
  318.    and without such frills as -F or -s,
  319.    is guaranteed to make it possible for a program receiving
  320.    the output to tell exactly what file names are present.  -Q  */
  321.  
  322. int quote_as_string;
  323.  
  324. /* The number of chars per hardware tab stop.  -T */
  325. int tabsize;
  326.  
  327. /* Nonzero means we are listing the working directory because no
  328.    non-option arguments were given. */
  329.  
  330. int dir_defaulted;
  331.  
  332. /* Nonzero means print each directory name before listing it. */
  333.  
  334. int print_dir_name;
  335.  
  336. /* The line length to use for breaking lines in many-per-line format.
  337.    Can be set with -w.  */
  338.  
  339. int line_length;
  340.  
  341. /* If nonzero, the file listing format requires that stat be called on
  342.    each file. */
  343.  
  344. int format_needs_stat;
  345.  
  346. void
  347. main (argc, argv)
  348.      int argc;
  349.      char **argv;
  350. {
  351.   register int i;
  352.   register struct pending *thispend;
  353.  
  354.   dir_defaulted = 1;
  355.   print_dir_name = 1;
  356.   pending_dirs = 0;
  357.   current_time = time ((long *) 0);
  358.  
  359.   program_name = argv[0];
  360.   i = decode_switches (argc, argv);
  361.  
  362.   format_needs_stat = sort_type == sort_time || sort_type == sort_size
  363.     || format == long_format
  364.     || trace_links || trace_dirs || indicator_style != none
  365.     || print_block_size || print_inode;
  366.  
  367.   nfiles = 100;
  368.   files = (struct file *) xmalloc (sizeof (struct file) * nfiles);
  369.   files_index = 0;
  370.  
  371.   clear_files ();
  372.  
  373.   if (i < argc)
  374.     dir_defaulted = 0;
  375.   for (; i < argc; i++)
  376.     gobble_file (argv[i], 1, "");
  377.  
  378.   if (dir_defaulted)
  379.     {
  380.       if (immediate_dirs)
  381.     gobble_file (".", 1, "");
  382.       else
  383.     queue_directory (".", 0);
  384.     }
  385.  
  386.   if (files_index)
  387.     {
  388.       sort_files ();
  389.       if (!immediate_dirs)
  390.     extract_dirs_from_files ("", 0);
  391.       /* `files_index' might be zero now.  */
  392.     }
  393.   if (files_index)
  394.     {
  395.       print_current_files ();
  396.       if (pending_dirs)
  397.     putchar ('\n');
  398.     }
  399.   else if (pending_dirs && pending_dirs->next == 0)
  400.     print_dir_name = 0;
  401.  
  402.   while (pending_dirs)
  403.     {
  404.       thispend = pending_dirs;
  405.       pending_dirs = pending_dirs->next;
  406.       print_dir (thispend->name, thispend->realname);
  407.       free (thispend->name);
  408.       if (thispend->realname)
  409.     free (thispend->realname);
  410.       free (thispend);
  411.       print_dir_name = 1;
  412.     }
  413.  
  414.   exit (0);
  415. }
  416.  
  417. struct option long_options[] =
  418. {
  419.   {"all", 0, 0, 'a'},
  420.   {"escape", 0, 0, 'b'},
  421.   {"directory", 0, 0, 'd'},
  422.   {"inode", 0, 0, 'i'},
  423.   {"kilobyte-file-size", 0, 0, 'k'},
  424.   {"numeric-uid-gid", 0, 0, 'n'},
  425.   {"hide-control-chars", 0, 0, 'q'},
  426.   {"reverse", 0, 0, 'r'},
  427.   {"size", 0, 0, 's'},
  428.   {"width", 1, 0, 'w'},
  429.   {"almost-all", 0, 0, 'A'},
  430.   {"ignore-backups", 0, 0, 'B'},
  431.   {"classify", 0, 0, 'F'},
  432.   {"file-type", 0, 0, 'F'},
  433.   {"ignore", 1, 0, 'I'},
  434.   {"dereference", 0, 0, 'L'},
  435.   {"literal", 0, 0, 'N'},
  436.   {"quote-name", 0, 0, 'Q'},
  437.   {"recursive", 0, 0, 'R'},
  438.   {"format", 1, 0, 12},
  439.   {"sort", 1, 0, 10},
  440.   {"tabsize", 1, 0, 'T'},
  441.   {"time", 1, 0, 11},
  442.   {0, 0, 0, 0}
  443. };
  444.  
  445. char *format_args[] =
  446. {
  447.   "verbose", "long", "commas", "horizontal", "across",
  448.   "vertical", "single-column", 0
  449. };
  450.  
  451. enum format formats[] =
  452. {
  453.   long_format, long_format, with_commas, horizontal, horizontal,
  454.   many_per_line, one_per_line
  455. };
  456.  
  457. char *sort_args[] =
  458. {
  459.   "none", "time", "size", 0
  460. };
  461.  
  462. enum sort_type sort_types[] =
  463. {
  464.   sort_none, sort_time, sort_size
  465. };
  466.  
  467. char *time_args[] =
  468. {
  469.   "access", "use", "status", 0
  470. };
  471.  
  472. enum time_type time_types[] =
  473. {
  474.   time_atime, time_atime, time_ctime
  475. };
  476.  
  477. /* Set all the option flags according to the switches specified.
  478.    Return the index of the first non-option argument.  */
  479.  
  480. int
  481. decode_switches (argc, argv)
  482.      int argc;
  483.      char **argv;
  484. {
  485.   register char *p;
  486.   int c;
  487.   int longind;
  488.  
  489.   qmark_funny_chars = 0;
  490.   quote_funny_chars = 0;
  491.  
  492.   /* initialize all switches to default settings */
  493.  
  494. #ifdef MULTI_COL
  495. #define PROGNAME "dir"
  496.   /* This is for the `dir' program.  */
  497.   format = many_per_line;
  498.   quote_funny_chars = 1;
  499. #else
  500. #ifdef LONG_FORMAT
  501. #define PROGNAME "vdir"
  502.   /* This is for the `vdir' program.  */
  503.   format = long_format;
  504.   quote_funny_chars = 1;
  505. #else
  506. #define PROGNAME "ls"
  507.   /* This is for the `ls' program.  */
  508.   if (isatty (1))
  509.     {
  510.       format = many_per_line;
  511.       qmark_funny_chars = 1;
  512.     }
  513.   else
  514.     {
  515.       format = one_per_line;
  516.       qmark_funny_chars = 0;
  517.     }
  518. #endif
  519. #endif
  520.  
  521.   time_type = time_mtime;
  522.   sort_type = sort_name;
  523.   sort_reverse = 0;
  524.   numeric_users = 0;
  525.   print_block_size = 0;
  526.   kilobyte_blocks = 0;
  527.   indicator_style = none;
  528.   print_inode = 0;
  529.   trace_links = 0;
  530.   trace_dirs = 0;
  531.   immediate_dirs = 0;
  532.   all_files = 0;
  533.   really_all_files = 0;
  534.   ignore_patterns = 0;
  535.   quote_as_string = 0;
  536.  
  537.   p = getenv ("COLUMNS");
  538.   line_length = p ? atoi (p) : 80;
  539.  
  540. #ifdef TIOCGWINSZ
  541.   {
  542.     struct winsize ws;
  543.  
  544.     if (ioctl (1, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0)
  545.       line_length = ws.ws_col;
  546.   }
  547. #endif
  548.  
  549.   p = getenv ("TABSIZE");
  550.   tabsize = p ? atoi (p) : 8;
  551.  
  552.   while ((c = getopt_long (argc, argv, "abcdgiklmnpqrstuw:xABCFI:LNQRST:U1",
  553.                long_options, &longind)) != EOF)
  554.     {
  555.       if (c == 0)
  556.     c = long_options[longind].val;
  557.       switch (c)
  558.     {
  559.     case 'a':
  560.       all_files = 1;
  561.       really_all_files = 1;
  562.       break;
  563.       
  564.     case 'b':
  565.       quote_funny_chars = 1;
  566.       qmark_funny_chars = 0;
  567.       break;
  568.       
  569.     case 'c':
  570.       time_type = time_ctime;
  571.       break;
  572.       
  573.     case 'd':
  574.       immediate_dirs = 1;
  575.       break;
  576.       
  577.     case 'g':
  578.       /* No effect.  For BSD compatibility. */
  579.       break;
  580.  
  581.     case 'i':
  582.       print_inode = 1;
  583.       break;
  584.       
  585.     case 'k':
  586.       kilobyte_blocks = 1;
  587.       break;
  588.       
  589.     case 'l':
  590.       format = long_format;
  591.       break;
  592.       
  593.     case 'm':
  594.       format = with_commas;
  595.       break;
  596.       
  597.     case 'n':
  598.       numeric_users = 1;
  599.       break;
  600.       
  601.     case 'p':
  602.       indicator_style = not_programs;
  603.       break;
  604.       
  605.     case 'q':
  606.       qmark_funny_chars = 1;
  607.       quote_funny_chars = 0;
  608.       break;
  609.       
  610.     case 'r':
  611.       sort_reverse = 1;
  612.       break;
  613.       
  614.     case 's':
  615.       print_block_size = 1;
  616.       break;
  617.       
  618.     case 't':
  619.       sort_type = sort_time;
  620.       break;
  621.       
  622.     case 'u':
  623.       time_type = time_atime;
  624.       break;
  625.       
  626.     case 'w':
  627.       line_length = atoi (optarg);
  628.       if (line_length < 1)
  629.         error (1, 0, "invalid line width: %s", optarg);
  630.       break;
  631.       
  632.     case 'x':
  633.       format = horizontal;
  634.       break;
  635.       
  636.     case 'A':
  637.       all_files = 1;
  638.       break;
  639.       
  640.     case 'B':
  641.       add_ignore_pattern ("*~");
  642.       add_ignore_pattern (".*~");
  643.       break;
  644.       
  645.     case 'C':
  646.       format = many_per_line;
  647.       break;
  648.       
  649.     case 'F':
  650.       indicator_style = all;
  651.       break;
  652.       
  653.     case 'I':
  654.       add_ignore_pattern (optarg);
  655.       break;
  656.       
  657.     case 'L':
  658.       trace_links = 1;
  659.       break;
  660.       
  661.     case 'N':
  662.       quote_funny_chars = 0;
  663.       qmark_funny_chars = 0;
  664.       break;
  665.       
  666.     case 'Q':
  667.       quote_as_string = 1;
  668.       quote_funny_chars = 1;
  669.       qmark_funny_chars = 0;
  670.       break;
  671.       
  672.     case 'R':
  673.       trace_dirs = 1;
  674.       break;
  675.       
  676.     case 'S':
  677.       sort_type = sort_size;
  678.       break;
  679.       
  680.     case 'T':
  681.       tabsize = atoi (optarg);
  682.       if (tabsize < 1)
  683.         error (1, 0, "invalid tab size: %s", optarg);
  684.       break;
  685.  
  686.     case 'U':
  687.       sort_type = sort_none;
  688.       break;
  689.  
  690.     case '1':
  691.       format = one_per_line;
  692.       break;
  693.       
  694.     case 10:        /* +sort */
  695.       longind = argmatch (optarg, sort_args);
  696.       if (longind < 0)
  697.         {
  698.           invalid_arg ("sort type", optarg, longind);
  699.           usage ();
  700.         }
  701.       sort_type = sort_types[longind];
  702.       break;
  703.  
  704.     case 11:        /* +time */
  705.       longind = argmatch (optarg, time_args);
  706.       if (longind < 0)
  707.         {
  708.           invalid_arg ("time type", optarg, longind);
  709.           usage ();
  710.         }
  711.       time_type = time_types[longind];
  712.       break;
  713.  
  714.     case 12:        /* +format */
  715.       longind = argmatch (optarg, format_args);
  716.       if (longind < 0)
  717.         {
  718.           invalid_arg ("format type", optarg, longind);
  719.           usage ();
  720.         }
  721.       format = formats[longind];
  722.       break;
  723.       
  724.     default:
  725.       usage ();
  726.     }
  727.     }
  728.  
  729.   return optind;
  730. }
  731.  
  732. /* Request that the directory named `name' have its contents listed later.
  733.    If `realname' is nonzero, it will be used instead of `name' when the
  734.    directory name is printed.  This allows symbolic links to directories
  735.    to be treated as regular directories but still be listed under their
  736.    real names. */
  737.  
  738. void
  739. queue_directory (name, realname)
  740.      char *name;
  741.      char *realname;
  742. {
  743.   struct pending *new;
  744.  
  745.   new = (struct pending *) xmalloc (sizeof (struct pending));
  746.   new->next = pending_dirs;
  747.   pending_dirs = new;
  748.   new->name = copystring (name);
  749.   if (realname)
  750.     new->realname = copystring (realname);
  751.   else
  752.     new->realname = 0;
  753. }
  754.  
  755. /* Read directory `name', and list the files in it.
  756.    If `realname' is nonzero, print its name instead of `name';
  757.    this is used for symbolic links to directories. */
  758.  
  759. void
  760. print_dir (name, realname)
  761.      char *name;
  762.      char *realname;
  763. {
  764.   register DIR *reading;
  765.   register struct direct *next;
  766.   register int total_blocks = 0;
  767.  
  768.   errno = 0;
  769.   reading = opendir (name);
  770.   if (!reading)
  771.     {
  772.       error (0, errno, "%s", name);
  773.       return;
  774.     }
  775.  
  776.   /* Read the directory entries, and insert the subfiles into the `files'
  777.      table.  */
  778.  
  779.   clear_files ();
  780.  
  781.   while (next = readdir (reading))
  782.     if (file_interesting (next))
  783.       total_blocks += gobble_file (next->d_name, 0, name);
  784.  
  785.   closedir (reading);
  786.  
  787.   /* Sort the directory contents.  */
  788.   sort_files ();
  789.  
  790.   /* If any member files are subdirectories, perhaps they should have their
  791.      contents listed rather than being mentioned here as files.  */
  792.  
  793.   if (trace_dirs)
  794.     extract_dirs_from_files (name, 1);
  795.  
  796.   if (print_dir_name)
  797.     {
  798.       if (realname)
  799.     printf ("%s:\n", realname);
  800.       else
  801.     printf ("%s:\n", name);
  802.     }
  803.  
  804.   if (format == long_format || print_block_size)
  805.     printf ("total %u\n", total_blocks);
  806.  
  807.   if (files_index)
  808.     print_current_files ();
  809.  
  810.   if (pending_dirs)
  811.     putchar ('\n');
  812. }
  813.  
  814. /* Add `pattern' to the list of patterns for which files that match are
  815.    not listed.  */
  816.  
  817. void
  818. add_ignore_pattern (pattern)
  819.      char *pattern;
  820. {
  821.   register struct ignore_pattern *ignore;
  822.  
  823.   ignore = (struct ignore_pattern *) xmalloc (sizeof (struct ignore_pattern));
  824.   ignore->pattern = pattern;
  825.   /* Add it to the head of the linked list. */
  826.   ignore->next = ignore_patterns;
  827.   ignore_patterns = ignore;
  828. }
  829.  
  830. /* Return nonzero if the file in `next' should be listed. */
  831.  
  832. int
  833. file_interesting (next)
  834.      register struct direct *next;
  835. {
  836.   register struct ignore_pattern *ignore;
  837.  
  838.   for (ignore = ignore_patterns; ignore; ignore = ignore->next)
  839.     if (glob_match (ignore->pattern, next->d_name, 1))
  840.       return 0;
  841.  
  842.   if (really_all_files
  843.       || next->d_name[0] != '.'
  844.       || (all_files
  845.       && next->d_name[1] != '\0'
  846.       && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
  847.     return 1;
  848.  
  849.   return 0;
  850. }
  851.  
  852. /* Enter and remove entries in the table `files'.  */
  853.  
  854. /* Empty the table of files. */
  855.  
  856. void
  857. clear_files ()
  858. {
  859.   register int i;
  860.  
  861.   for (i = 0; i < files_index; i++)
  862.     {
  863.       free (files[i].name);
  864.       if (files[i].linkname)
  865.     free (files[i].linkname);
  866.     }
  867.  
  868.   files_index = 0;
  869.   block_size_size = 4;
  870. }
  871.  
  872. /* Add a file to the current table of files.
  873.    Verify that the file exists, and print an error message if it does not.
  874.    Return the number of blocks that the file occupies.  */
  875.  
  876. int
  877. gobble_file (name, explicit_arg, dirname)
  878.      char *name;
  879.      int explicit_arg;
  880.      char *dirname;
  881. {
  882.   register int blocks;
  883.   register int val;
  884.   register char *path;
  885.  
  886.   if (files_index == nfiles)
  887.     {
  888.       nfiles *= 2;
  889.       files = (struct file *) xrealloc (files, sizeof (struct file) * nfiles);
  890.     }
  891.  
  892.   files[files_index].linkname = 0;
  893.   files[files_index].linkmode = 0;
  894.  
  895.   if (explicit_arg || format_needs_stat)
  896.     {
  897.       /* `path' is the absolute pathname of this file. */
  898.  
  899.       if (name[0] == '/' || dirname[0] == 0)
  900.     path = name;
  901.       else
  902.     {
  903.       path = (char *) alloca (strlen (name) + strlen (dirname) + 2);
  904.       attach (path, dirname, name);
  905.     }
  906.  
  907.       if (trace_links)
  908.     {
  909.       val = stat (path, &files[files_index].stat);
  910.       if (val < 0)
  911.         /* Perhaps a symbolically-linked to file doesn't exist; stat
  912.            the link instead. */
  913.         val = lstat (path, &files[files_index].stat);
  914.     }
  915.       else
  916.     val = lstat (path, &files[files_index].stat);
  917.       if (val < 0)
  918.     {
  919.       error (0, errno, "%s", path);
  920.       return 0;
  921.     }
  922.  
  923. #ifdef S_IFLNK
  924.       if ((files[files_index].stat.st_mode & S_IFMT) == S_IFLNK)
  925.     {
  926.       char *linkpath;
  927.       struct stat linkstats;
  928.  
  929.       get_link_name (path, &files[files_index]);
  930.       linkpath = make_link_path (path, files[files_index].linkname);
  931.  
  932.       /* Stat the file linked to; automatically trace it in non-long
  933.          listings, get its mode for the filetype indicator in long
  934.          listings. */
  935.       if (linkpath && lstat (linkpath, &linkstats) == 0)
  936.         {
  937.           if ((linkstats.st_mode & S_IFMT) == S_IFDIR
  938.           && explicit_arg && format != long_format)
  939.         {
  940.           char *tempname;
  941.  
  942.           /* Symbolic links to directories that are mentioned on the
  943.              command line are automatically traced if not being
  944.              listed as files. */
  945.           if (!immediate_dirs)
  946.             {
  947.               tempname = name;
  948.               name = linkpath;
  949.               linkpath = files[files_index].linkname;
  950.               files[files_index].linkname = tempname;
  951.             }
  952.           files[files_index].stat = linkstats;
  953.         }
  954.           else
  955.         files[files_index].linkmode = linkstats.st_mode;
  956.         }
  957.       if (linkpath)
  958.         free (linkpath);
  959.     }
  960. #endif
  961.  
  962.       switch (files[files_index].stat.st_mode & S_IFMT)
  963.     {
  964. #ifdef S_IFLNK
  965.     case S_IFLNK:
  966.       files[files_index].filetype = symbolic_link;
  967.       break;
  968. #endif
  969.  
  970.     case S_IFDIR:
  971.       if (explicit_arg && !immediate_dirs)
  972.         files[files_index].filetype = arg_directory;
  973.       else
  974.         files[files_index].filetype = directory;
  975.       break;
  976.  
  977.     default:
  978.       files[files_index].filetype = normal;
  979.       break;
  980.     }
  981.  
  982.       blocks = convert_blocks (ST_NBLOCKS (files[files_index].stat),
  983.                    kilobyte_blocks);
  984.       if (blocks >= 10000 && block_size_size < 5)
  985.     block_size_size = 5;
  986.       if (blocks >= 100000 && block_size_size < 6)
  987.     block_size_size = 6;
  988.       if (blocks >= 1000000 && block_size_size < 7)
  989.     block_size_size = 7;
  990.     }
  991.   else
  992.     blocks = 0;
  993.  
  994.   files[files_index].name = copystring (name);
  995.   files_index++;
  996.  
  997.   return blocks;
  998. }
  999.  
  1000. #ifdef S_IFLNK
  1001.  
  1002. /* Put the name of the file that `filename' is a symbolic link to
  1003.    into the `linkname' field of `f'. */
  1004.  
  1005. void
  1006. get_link_name (filename, f)
  1007.      char *filename;
  1008.      struct file *f;
  1009. {
  1010.   register char *linkbuf;
  1011.   register int bufsiz = f->stat.st_size;
  1012.  
  1013.   linkbuf = (char *) xmalloc (bufsiz + 1);
  1014.   linkbuf[bufsiz] = 0;
  1015.   if (readlink (filename, linkbuf, bufsiz) < 0)
  1016.     {
  1017.       error (0, errno, "%s", filename);
  1018.       free (linkbuf);
  1019.     }
  1020.   else
  1021.     f->linkname = linkbuf;
  1022. }
  1023.  
  1024. /* If `linkname' is a relative path and `path' contains one or more
  1025.    leading directories, return `linkname' with those directories
  1026.    prepended; otherwise, return a copy of `linkname'.
  1027.    If `linkname' is zero, return zero. */
  1028.  
  1029. char *
  1030. make_link_path (path, linkname)
  1031.      char *path;
  1032.      char *linkname;
  1033. {
  1034.   char *linkbuf;
  1035.   int bufsiz;
  1036.  
  1037.   if (linkname == 0)
  1038.     return 0;
  1039.  
  1040.   if (*linkname == '/')
  1041.     return copystring (linkname);
  1042.  
  1043.   /* The link is to a relative path.  Prepend any leading path
  1044.      in `path' to the link name. */
  1045.   linkbuf = rindex (path, '/');
  1046.   if (linkbuf == 0)
  1047.     return copystring (linkname);
  1048.  
  1049.   bufsiz = linkbuf - path + 1;
  1050.   linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
  1051.   strncpy (linkbuf, path, bufsiz);
  1052.   strcpy (linkbuf + bufsiz, linkname);
  1053.   return linkbuf;
  1054. }
  1055. #endif
  1056.  
  1057. /* Remove any entries from `files' that are for directories,
  1058.    and queue them to be listed as directories instead.
  1059.    `dirname' is the prefix to prepend to each dirname
  1060.    to make it correct relative to ls's working dir.
  1061.    `recursive' is nonzero if we should not treat `.' and `..' as dirs.
  1062.    This is desirable when processing directories recursively.  */
  1063.  
  1064. void
  1065. extract_dirs_from_files (dirname, recursive)
  1066.      char *dirname;
  1067.      int recursive;
  1068. {
  1069.   register int i, j;
  1070.   register char *path;
  1071.   int dirlen;
  1072.  
  1073.   dirlen = strlen (dirname) + 2;
  1074.   /* Queue the directories last one first, because queueing reverses the
  1075.      order.  */
  1076.   for (i = files_index - 1; i >= 0; i--)
  1077.     if ((files[i].filetype == directory || files[i].filetype == arg_directory)
  1078.     && (!recursive || is_not_dot_or_dotdot (files[i].name)))
  1079.       {
  1080.     if (files[i].name[0] == '/' || dirname[0] == 0)
  1081.       {
  1082.         queue_directory (files[i].name, files[i].linkname);
  1083.       }
  1084.     else
  1085.       {
  1086.         path = (char *) xmalloc (strlen (files[i].name) + dirlen);
  1087.         attach (path, dirname, files[i].name);
  1088.         queue_directory (path, files[i].linkname);
  1089.         free (path);
  1090.       }
  1091.     if (files[i].filetype == arg_directory)
  1092.       free (files[i].name);
  1093.       }
  1094.  
  1095.   /* Now delete the directories from the table, compacting all the remaining
  1096.      entries.  */
  1097.  
  1098.   for (i = 0, j = 0; i < files_index; i++)
  1099.     if (files[i].filetype != arg_directory)
  1100.       files[j++] = files[i];
  1101.   files_index = j;
  1102. }
  1103.  
  1104. /* Return non-zero if `name' doesn't end in `.' or `..'
  1105.    This is so we don't try to recurse on `././././. ...' */
  1106.  
  1107. int
  1108. is_not_dot_or_dotdot (name)
  1109.      char *name;
  1110. {
  1111.   char *t;
  1112.  
  1113.   t = rindex (name, '/');
  1114.   if (t)
  1115.     name = t + 1;
  1116.  
  1117.   if (name[0] == '.'
  1118.       && (name[1] == '\0'
  1119.       || (name[1] == '.' && name[2] == '\0')))
  1120.     return 0;
  1121.  
  1122.   return 1;
  1123. }
  1124.  
  1125. /* Sort the files now in the table.  */
  1126.  
  1127. void
  1128. sort_files ()
  1129. {
  1130.   int (*func) ();
  1131.  
  1132.   switch (sort_type)
  1133.     {
  1134.     case sort_none:
  1135.       return;
  1136.     case sort_time:
  1137.       switch (time_type)
  1138.     {
  1139.     case time_ctime:
  1140.       func = sort_reverse ? rev_cmp_ctime : compare_ctime;
  1141.       break;
  1142.     case time_mtime:
  1143.       func = sort_reverse ? rev_cmp_mtime : compare_mtime;
  1144.       break;
  1145.     case time_atime:
  1146.       func = sort_reverse ? rev_cmp_atime : compare_atime;
  1147.       break;
  1148.     }
  1149.       break;
  1150.     case sort_name:
  1151.       func = sort_reverse ? rev_cmp_name : compare_name;
  1152.       break;
  1153.     case sort_size:
  1154.       func = sort_reverse ? rev_cmp_size : compare_size;
  1155.       break;
  1156.     }
  1157.  
  1158.   qsort (files, files_index, sizeof (struct file), func);
  1159. }
  1160.  
  1161. /* Comparison routines for sorting the files. */
  1162.  
  1163. int
  1164. compare_ctime (file1, file2)
  1165.      struct file *file1, *file2;
  1166. {
  1167.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1168. }
  1169.  
  1170. int
  1171. rev_cmp_ctime (file2, file1)
  1172.      struct file *file1, *file2;
  1173. {
  1174.   return longdiff (file2->stat.st_ctime, file1->stat.st_ctime);
  1175. }
  1176.  
  1177. int
  1178. compare_mtime (file1, file2)
  1179.      struct file *file1, *file2;
  1180. {
  1181.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1182. }
  1183.  
  1184. int
  1185. rev_cmp_mtime (file2, file1)
  1186.      struct file *file1, *file2;
  1187. {
  1188.   return longdiff (file2->stat.st_mtime, file1->stat.st_mtime);
  1189. }
  1190.  
  1191. int
  1192. compare_atime (file1, file2)
  1193.      struct file *file1, *file2;
  1194. {
  1195.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1196. }
  1197.  
  1198. int
  1199. rev_cmp_atime (file2, file1)
  1200.      struct file *file1, *file2;
  1201. {
  1202.   return longdiff (file2->stat.st_atime, file1->stat.st_atime);
  1203. }
  1204.  
  1205. int
  1206. compare_size (file1, file2)
  1207.      struct file *file1, *file2;
  1208. {
  1209.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1210. }
  1211.  
  1212. int
  1213. rev_cmp_size (file2, file1)
  1214.      struct file *file1, *file2;
  1215. {
  1216.   return longdiff (file2->stat.st_size, file1->stat.st_size);
  1217. }
  1218.  
  1219. int
  1220. compare_name (file1, file2)
  1221.      struct file *file1, *file2;
  1222. {
  1223.   return strcmp (file1->name, file2->name);
  1224. }
  1225.  
  1226. int
  1227. rev_cmp_name (file2, file1)
  1228.      struct file *file1, *file2;
  1229. {
  1230.   return strcmp (file1->name, file2->name);
  1231. }
  1232.  
  1233. /* List all the files now in the table.  */
  1234.  
  1235. void
  1236. print_current_files ()
  1237. {
  1238.   register int i;
  1239.  
  1240.   switch (format)
  1241.     {
  1242.     case one_per_line:
  1243.       for (i = 0; i < files_index; i++)
  1244.     {
  1245.       print_file_name_and_frills (files + i);
  1246.       putchar ('\n');
  1247.     }
  1248.       break;
  1249.  
  1250.     case many_per_line:
  1251.       print_many_per_line ();
  1252.       break;
  1253.  
  1254.     case horizontal:
  1255.       print_horizontal ();
  1256.       break;
  1257.  
  1258.     case with_commas:
  1259.       print_with_commas ();
  1260.       break;
  1261.  
  1262.     case long_format:
  1263.       for (i = 0; i < files_index; i++)
  1264.     {
  1265.       print_long_format (files + i);
  1266.       putchar ('\n');
  1267.     }
  1268.       break;
  1269.     }
  1270. }
  1271.  
  1272. void
  1273. print_long_format (f)
  1274.      struct file *f;
  1275. {
  1276.   char modebuf[20];
  1277.   char timebuf[40];
  1278.   long when;
  1279.  
  1280.   mode_string (f->stat.st_mode, modebuf);
  1281.   modebuf[10] = 0;
  1282.  
  1283.   switch (time_type)
  1284.     {
  1285.     case time_ctime:
  1286.       when = f->stat.st_ctime;
  1287.       break;
  1288.     case time_mtime:
  1289.       when = f->stat.st_mtime;
  1290.       break;
  1291.     case time_atime:
  1292.       when = f->stat.st_atime;
  1293.       break;
  1294.     }
  1295.  
  1296.   strcpy (timebuf, ctime (&when));
  1297.   if (current_time - when > 6L * 30L * 24L * 60L * 60L
  1298.       || current_time - when < 0L)
  1299.     {
  1300.       /* The file is fairly old or in the future.
  1301.      POSIX says the cutoff is 6 months old;
  1302.      approximate this by 6*30 days.
  1303.      Show the year instead of the time of day.  */
  1304.       strcpy (timebuf + 11, timebuf + 19);
  1305.     }
  1306.   timebuf[16] = 0;
  1307.  
  1308.   if (print_inode)
  1309.     printf ("%6u ", f->stat.st_ino);
  1310.  
  1311.   if (print_block_size)
  1312.     printf ("%*u ", block_size_size, convert_blocks (ST_NBLOCKS (f->stat),
  1313.                              kilobyte_blocks));
  1314.  
  1315.   /* The space between the mode and the number of links is the POSIX
  1316.      "optional alternate access method flag". */
  1317.   printf ("%s %3u ", modebuf, f->stat.st_nlink);
  1318.  
  1319.   if (numeric_users)
  1320.     printf ("%-8u ", f->stat.st_uid);
  1321.   else
  1322.     printf ("%-8s ", getuser (f->stat.st_uid));
  1323.  
  1324.   if (numeric_users)
  1325.     printf ("%-8u ", f->stat.st_gid);
  1326.   else
  1327.     printf ("%-8s ", getgroup (f->stat.st_gid));
  1328.  
  1329.   if ((f->stat.st_mode & S_IFMT) == S_IFCHR
  1330.       || (f->stat.st_mode & S_IFMT) == S_IFBLK)
  1331.     printf ("%3u, %3u ", major (f->stat.st_rdev), minor (f->stat.st_rdev));
  1332.   else
  1333.     printf ("%8lu ", f->stat.st_size);
  1334.  
  1335.   printf ("%s ", timebuf + 4);
  1336.  
  1337.   print_name_with_quoting (f->name);
  1338.  
  1339.   if (f->filetype == symbolic_link)
  1340.     {
  1341.       if (f->linkname)
  1342.     {
  1343.       fputs (" -> ", stdout);
  1344.       print_name_with_quoting (f->linkname);
  1345.       if (indicator_style != none)
  1346.         print_type_indicator (f->linkmode);
  1347.     }
  1348.     }
  1349.   else if (indicator_style != none)
  1350.     print_type_indicator (f->stat.st_mode);
  1351. }
  1352.  
  1353. void
  1354. print_name_with_quoting (p)
  1355.      register char *p;
  1356. {
  1357.   register unsigned char c;
  1358.  
  1359.   if (quote_as_string)
  1360.     putchar ('"');
  1361.  
  1362.   while (c = *p++)
  1363.     {
  1364.       if (quote_funny_chars)
  1365.     {
  1366.       switch (c)
  1367.         {
  1368.         case '\\':
  1369.           printf ("\\\\");
  1370.           break;
  1371.  
  1372.         case '\n':
  1373.           printf ("\\n");
  1374.           break;
  1375.  
  1376.         case '\b':
  1377.           printf ("\\b");
  1378.           break;
  1379.  
  1380.         case '\r':
  1381.           printf ("\\r");
  1382.           break;
  1383.  
  1384.         case '\t':
  1385.           printf ("\\t");
  1386.           break;
  1387.  
  1388.         case '\f':
  1389.           printf ("\\f");
  1390.           break;
  1391.  
  1392.         case ' ':
  1393.           printf ("\\ ");
  1394.           break;
  1395.  
  1396.         case '"':
  1397.           printf ("\\\"");
  1398.           break;
  1399.  
  1400.         default:
  1401.           if (c > 040 && c < 0177)
  1402.         putchar (c);
  1403.           else
  1404.         printf ("\\%03o", (unsigned int) c);
  1405.         }
  1406.     }
  1407.       else
  1408.     {
  1409.       if (c >= 040 && c < 0177)
  1410.         putchar (c);
  1411.       else if (!qmark_funny_chars)
  1412.         putchar (c);
  1413.       else
  1414.         putchar ('?');
  1415.     }
  1416.     }
  1417.  
  1418.   if (quote_as_string)
  1419.     putchar ('"');
  1420. }
  1421.  
  1422. /* Print the file name of `f' with appropriate quoting.
  1423.    Also print file size, inode number, and filetype indicator character,
  1424.    as requested by switches.  */
  1425.  
  1426. void
  1427. print_file_name_and_frills (f)
  1428.      struct file *f;
  1429. {
  1430.   if (print_inode)
  1431.     printf ("%6u ", f->stat.st_ino);
  1432.  
  1433.   if (print_block_size)
  1434.     printf ("%*u ", block_size_size, convert_blocks (ST_NBLOCKS (f->stat),
  1435.                              kilobyte_blocks));
  1436.  
  1437.   print_name_with_quoting (f->name);
  1438.  
  1439.   if (indicator_style != none)
  1440.     print_type_indicator (f->stat.st_mode);
  1441. }
  1442.  
  1443. void
  1444. print_type_indicator (mode)
  1445.      unsigned int mode;
  1446. {
  1447.   switch (mode & S_IFMT)
  1448.     {
  1449.     case S_IFDIR:
  1450.       putchar ('/');
  1451.       break;
  1452.  
  1453. #ifdef S_IFLNK
  1454.     case S_IFLNK:
  1455.       putchar ('@');
  1456.       break;
  1457. #endif
  1458.  
  1459. #ifdef S_IFIFO
  1460.     case S_IFIFO:
  1461.       putchar ('|');
  1462.       break;
  1463. #endif
  1464.  
  1465. #ifdef S_IFSOCK
  1466.     case S_IFSOCK:
  1467.       putchar ('=');
  1468.       break;
  1469. #endif
  1470.  
  1471.     case S_IFREG:
  1472.       if (indicator_style == all
  1473.       && (mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1474.     putchar ('*');
  1475.       break;
  1476.     }
  1477. }
  1478.  
  1479. int
  1480. length_of_file_name_and_frills (f)
  1481.      struct file *f;
  1482. {
  1483.   register char *p = f->name;
  1484.   register char c;
  1485.   register int len = 0;
  1486.  
  1487.   if (print_inode)
  1488.     len += 7;
  1489.  
  1490.   if (print_block_size)
  1491.     len += 1 + block_size_size;
  1492.  
  1493.   if (quote_as_string)
  1494.     len += 2;
  1495.  
  1496.   while (c = *p++)
  1497.     {
  1498.       if (quote_funny_chars)
  1499.     {
  1500.       switch (c)
  1501.         {
  1502.         case '\\':
  1503.         case '\n':
  1504.         case '\b':
  1505.         case '\r':
  1506.         case '\t':
  1507.         case '\f':
  1508.         case ' ':
  1509.           len += 2;
  1510.           break;
  1511.  
  1512.         case '"':
  1513.           if (quote_as_string)
  1514.         len += 2;
  1515.           else
  1516.         len += 1;
  1517.           break;
  1518.  
  1519.         default:
  1520.           if (c >= 040 && c < 0177)
  1521.         len += 1;
  1522.           else
  1523.         len += 4;
  1524.         }
  1525.     }
  1526.       else
  1527.     len += 1;
  1528.     }
  1529.  
  1530.   if (indicator_style != none)
  1531.     {
  1532.       unsigned filetype = f->stat.st_mode & S_IFMT;
  1533.  
  1534.       if (filetype == S_IFREG)
  1535.     {
  1536.       if (indicator_style == all
  1537.           && (f->stat.st_mode & (S_IEXEC | S_IEXEC >> 3 | S_IEXEC >> 6)))
  1538.         len += 1;
  1539.     }
  1540.       else if (filetype != S_IFBLK && filetype != S_IFCHR)
  1541.     len += 1;
  1542.     }
  1543.  
  1544.   return len;
  1545. }
  1546.  
  1547. void
  1548. print_many_per_line ()
  1549. {
  1550.   int filesno;            /* Index into files. */
  1551.   int row;            /* Current row. */
  1552.   int max_name_length;        /* Length of longest file name + frills. */
  1553.   int name_length;        /* Length of each file name + frills. */
  1554.   int pos;            /* Current character column. */
  1555.   int cols;            /* Number of files across. */
  1556.   int rows;            /* Maximum number of files down. */
  1557.  
  1558.   /* Compute the maximum file name length.  */
  1559.   max_name_length = 0;
  1560.   for (filesno = 0; filesno < files_index; filesno++)
  1561.     {
  1562.       name_length = length_of_file_name_and_frills (files + filesno);
  1563.       if (name_length > max_name_length)
  1564.     max_name_length = name_length;
  1565.     }
  1566.  
  1567.   /* Allow at least two spaces between names.  */
  1568.   max_name_length += 2;
  1569.  
  1570.   /* Calculate the maximum number of columns that will fit. */
  1571.   cols = line_length / max_name_length;
  1572.   if (cols == 0)
  1573.     cols = 1;
  1574.   /* Calculate the number of rows that will be in each column except possibly
  1575.      for a short column on the right. */
  1576.   rows = files_index / cols + (files_index % cols != 0);
  1577.   /* Recalculate columns based on rows. */
  1578.   cols = files_index / rows + (files_index % rows != 0);
  1579.  
  1580.   for (row = 0; row < rows; row++)
  1581.     {
  1582.       filesno = row;
  1583.       pos = 0;
  1584.       /* Print the next row.  */
  1585.       while (1)
  1586.     {
  1587.       print_file_name_and_frills (files + filesno);
  1588.       name_length = length_of_file_name_and_frills (files + filesno);
  1589.  
  1590.       filesno += rows;
  1591.       if (filesno >= files_index)
  1592.         break;
  1593.  
  1594.       indent (pos + name_length, pos + max_name_length);
  1595.       pos += max_name_length;
  1596.     }
  1597.       putchar ('\n');
  1598.     }
  1599. }
  1600.  
  1601. void
  1602. print_horizontal ()
  1603. {
  1604.   int filesno;
  1605.   int max_name_length;
  1606.   int name_length;
  1607.   int cols;
  1608.   int pos;
  1609.  
  1610.   /* Compute the maximum file name length.  */
  1611.   max_name_length = 0;
  1612.   for (filesno = 0; filesno < files_index; filesno++)
  1613.     {
  1614.       name_length = length_of_file_name_and_frills (files + filesno);
  1615.       if (name_length > max_name_length)
  1616.     max_name_length = name_length;
  1617.     }
  1618.  
  1619.   /* Allow two spaces between names.  */
  1620.   max_name_length += 2;
  1621.  
  1622.   cols = line_length / max_name_length;
  1623.   if (cols == 0)
  1624.     cols = 1;
  1625.  
  1626.   pos = 0;
  1627.   name_length = 0;
  1628.  
  1629.   for (filesno = 0; filesno < files_index; filesno++)
  1630.     {
  1631.       if (filesno != 0)
  1632.     {
  1633.       if (filesno % cols == 0)
  1634.         {
  1635.           putchar ('\n');
  1636.           pos = 0;
  1637.         }
  1638.       else
  1639.         {
  1640.           indent (pos + name_length, pos + max_name_length);
  1641.           pos += max_name_length;
  1642.         }
  1643.     }
  1644.  
  1645.       print_file_name_and_frills (files + filesno);
  1646.  
  1647.       name_length = length_of_file_name_and_frills (files + filesno);
  1648.     }
  1649.   putchar ('\n');
  1650. }
  1651.  
  1652. void
  1653. print_with_commas ()
  1654. {
  1655.   int filesno;
  1656.   int pos, old_pos;
  1657.  
  1658.   pos = 0;
  1659.  
  1660.   for (filesno = 0; filesno < files_index; filesno++)
  1661.     {
  1662.       old_pos = pos;
  1663.  
  1664.       pos += length_of_file_name_and_frills (files + filesno);
  1665.       if (filesno + 1 < files_index)
  1666.     pos += 2;        /* For the comma and space */
  1667.  
  1668.       if (old_pos != 0 && pos >= line_length)
  1669.     {
  1670.       putchar ('\n');
  1671.       pos -= old_pos;
  1672.     }
  1673.  
  1674.       print_file_name_and_frills (files + filesno);
  1675.       if (filesno + 1 < files_index)
  1676.     {
  1677.       putchar (',');
  1678.       putchar (' ');
  1679.     }
  1680.     }
  1681.   putchar ('\n');
  1682. }
  1683.  
  1684. struct userid
  1685. {
  1686.   int uid;
  1687.   char *name;
  1688.   struct userid *next;
  1689. };
  1690.  
  1691. struct userid *user_alist;
  1692.  
  1693. /* Translate `uid' to a login name, with cache.  */
  1694.  
  1695. char *
  1696. getuser (uid)
  1697.      int uid;
  1698. {
  1699.   register struct userid *tail;
  1700.   struct passwd *pwent;
  1701.   char usernum_string[20];
  1702.  
  1703.   for (tail = user_alist; tail; tail = tail->next)
  1704.     if (tail->uid == uid)
  1705.       return tail->name;
  1706.  
  1707.   pwent = getpwuid (uid);
  1708.   tail = (struct userid *) xmalloc (sizeof (struct userid));
  1709.   tail->uid = uid;
  1710.   tail->next = user_alist;
  1711.   if (pwent == 0)
  1712.     {
  1713.       sprintf (usernum_string, "%u", uid);
  1714.       tail->name = copystring (usernum_string);
  1715.     }
  1716.   else
  1717.     tail->name = copystring (pwent->pw_name);
  1718.   user_alist = tail;
  1719.   return tail->name;
  1720. }
  1721.  
  1722. /* We use the same struct as for userids.  */
  1723. struct userid *group_alist;
  1724.  
  1725. /* Translate `gid' to a group name, with cache.  */
  1726.  
  1727. char *
  1728. getgroup (gid)
  1729.      int gid;
  1730. {
  1731.   register struct userid *tail;
  1732.   struct group *grent;
  1733.   char groupnum_string[20];
  1734.  
  1735.   for (tail = group_alist; tail; tail = tail->next)
  1736.     if (tail->uid == gid)
  1737.       return tail->name;
  1738.  
  1739.   grent = getgrgid (gid);
  1740.   tail = (struct userid *) xmalloc (sizeof (struct userid));
  1741.   tail->uid = gid;
  1742.   tail->next = group_alist;
  1743.   if (grent == 0)
  1744.     {
  1745.       sprintf (groupnum_string, "%u", gid);
  1746.       tail->name = copystring (groupnum_string);
  1747.     }
  1748.   else
  1749.     tail->name = copystring (grent->gr_name);
  1750.   group_alist = tail;
  1751.   return tail->name;
  1752. }
  1753.  
  1754. /* Assuming cursor is at position `from', indent up to position `to'.  */
  1755.  
  1756. void
  1757. indent (from, to)
  1758.      int from, to;
  1759. {
  1760.   while (from < to)
  1761.     {
  1762.       if (to / tabsize > from / tabsize)
  1763.     {
  1764.       putchar ('\t');
  1765.       from += tabsize - from % tabsize;
  1766.     }
  1767.       else
  1768.     {
  1769.       putchar (' ');
  1770.       from++;
  1771.     }
  1772.     }
  1773. }
  1774.  
  1775. /* Low level subroutines of general use,
  1776.    not specifically related to the task of listing a directory.  */
  1777.  
  1778. char *
  1779. xrealloc (obj, size)
  1780.      char *obj;
  1781.      int size;
  1782. {
  1783.   char *val = realloc (obj, size);
  1784.  
  1785.   if (!val)
  1786.     error (1, 0, "virtual memory exhausted");
  1787.  
  1788.   return val;
  1789. }
  1790.  
  1791. char *
  1792. xmalloc (size)
  1793.      int size;
  1794. {
  1795.   char *val = malloc (size);
  1796.  
  1797.   if (!val)
  1798.     error (1, 0, "virtual memory exhausted");
  1799.  
  1800.   return val;
  1801. }
  1802.  
  1803. /* Return a newly allocated copy of `string'. */
  1804.  
  1805. char *
  1806. copystring (string)
  1807.      char *string;
  1808. {
  1809.   return strcpy ((char *) xmalloc (strlen (string) + 1), string);
  1810. }
  1811.  
  1812. /* Put `dirname/name' into `dest', handling `.' and `/' properly. */
  1813.  
  1814. void
  1815. attach (dest, dirname, name)
  1816.      char *dest, *dirname, *name;
  1817. {
  1818.   char *dirnamep = dirname;
  1819.  
  1820.   /* Copy dirname if it is not ".". */
  1821.   if (dirname[0] != '.' || dirname[1] != 0)
  1822.     {
  1823.       while (*dirnamep)
  1824.     *dest++ = *dirnamep++;
  1825.       /* Add '/' if `dirname' doesn't already end with it. */
  1826.       if (dirnamep > dirname && dirnamep[-1] != '/')
  1827.     *dest++ = '/';
  1828.     }
  1829.   while (*name)
  1830.     *dest++ = *name++;
  1831.   *dest = 0;
  1832. }
  1833.  
  1834. void
  1835. usage ()
  1836. {
  1837.   fprintf (stderr, "\
  1838. Usage: %s [-abcdgiklmnpqrstuxABCFLNQRSU1] [-w cols] [-T cols] [-I pattern]\n\
  1839.        [+all] [+escape] [+directory] [+inode] [+kilobyte-file-size]\n\
  1840.        [+numeric-uid-gid] [+hide-control-chars] [+reverse] [+size]\n\
  1841.        [+width cols] [+tabsize cols] [+almost-all] [+ignore-backups]\n",
  1842.        program_name);
  1843.   fprintf (stderr, "\
  1844.        [+classify] [+file-type] [+ignore pattern] [+dereference] [+literal]\n\
  1845.        [+quote-name] [+recursive] [+sort {none,time,size}]\n\
  1846.        [+format {long,verbose,commas,across,vertical,single-column}]\n\
  1847.        [+time {access,use,status}] [path...]\n");
  1848.   exit (1);
  1849. }
  1850.